package mahjong;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import javax.swing.JOptionPane;

/**
 * This class handles the HighScores objects
 *
 */

public class HighScoreHandler 
{

	/** Prompt user for his/her name and save current score as a high score.
	 */
	public static void saveHighScore(String layout, Viewer v, int time)
	{
		HighScores hs = loadHighScores();
		HighScoreList hl = hs.getHighScores(layout);
		if(hl.canAdd(time))
		{
			String name = JOptionPane.showInputDialog("Your name:");
			hl.addHighScore(new Score(name, time));
			saveHighScore(hs);
			JOptionPane.showMessageDialog(v, hl.getHighScores());
		}
		
	}

	/** Save high scores.
	 * @param hs the HighScore object to be saved.
	 */
	private static void saveHighScore(HighScores hs)
	{
		try 
		{
			FileOutputStream f_out = new FileOutputStream("highscores.gamefile");
			ObjectOutputStream obj_out = new ObjectOutputStream (f_out);
			obj_out.writeObject (hs);
		} catch (Exception exc) {
			System.out.println("There was an error saving your highscore.");
		} 
	}

	/** Load current layout's hish score.
	 * @return a HighScore object containing the score information.
	 */
	private static HighScores loadHighScores()
	{
		try {
			InputStream f_in = new FileInputStream("highscores.gamefile");
			ObjectInputStream obj_in = new ObjectInputStream(f_in);
			Object obj = obj_in.readObject();
			if(obj instanceof HighScores)
			{
				HighScores hs = (HighScores) obj;
				return hs;
			}
			return new HighScores();
		} catch (Exception e) 
		{
			HighScores hs = new HighScores();
			return hs;
		}
	}
	
	/** Display the high scores in a message box.
	 * @param layout the layout for which the highscore is displayed.
	 * @param v the panel on which is message box is to be displayed.
	 */ 
	public static void displayHighScores(String layout, Viewer v)
	{
		HighScores hs = loadHighScores();
		HighScoreList hl = hs.getHighScores(layout);
		JOptionPane.showMessageDialog(v, hl.getHighScores());
	}
	
}
